'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: http.py
* @Time: 2025/9/17
* @All Rights Reserve By Brtc
'''
import logging
import os

from flask import Flask
from flask_cors import CORS
from flask_login import LoginManager
from flask_migrate import Migrate
from config.config import Config
from internal.exception.exception import CustomException
from internal.extension import logging_extension, redis_extension, celery_extension
from internal.middleware.middleware import Middleware
from internal.router.router import Router
from pkg.response import json
from pkg.response.http_code import HttpCode
from pkg.response.response import Response
from pkg.sqlachemy.sqlalchemy import SQLAlchemy


class Http(Flask):
    def __init__(self, *args, config:Config ,
                 db = SQLAlchemy,
                 migrate:Migrate,
                 login_manager:LoginManager,
                 middleware:Middleware,
                 router:Router, **kwargs):
        """父类的初始化"""
        super().__init__(*args, **kwargs)
        logging_extension.init_app(self)

        # 异常服务注册
        self.register_error_handler(Exception, self._register_error_handler)
        # 初始化服务器的配置
        self.config.from_object(config)

        #初始化数据库
        db.init_app(self)

        #初始化Redis
        redis_extension.init_app(self)

        #数据迁移
        """  
        1、 flask --app app.http.app db init
        2、修改你的表结构
        3、flask  --app app.http.app db migrate -m "XXX"
        4、flask  --app app.http.app db upgrade
        """
        migrate.init_app(self, db, directory="internal/migration")

        #初始化登录组件
        login_manager.init_app(self)

        # 跨域配置
        CORS(self, resources={
            f"/*": {
                "origins": "*",
                "supports_credentials": True,
                # 以下配置可以不设置
                "methods": ["GET", "POST","OPTION"],
                "allow_headers": ["Content-Type"],
            }
        })

        # 初始化Celery异步任务
        celery_extension.init_app(self)

        # 添加中间件
        login_manager.request_loader(middleware.request_loader)
        # 初始化router
        router.register_router(self)


    def _register_error_handler(self, error:Exception):
        logging.error("发生了异常: %s", error, exc_info=True)

        if isinstance(error, CustomException):
            return json(
                Response(code=error.code,
                         message=error.message,
                         data=error.data if error.data else {})
            )

        if os.getenv("FLASK_ENV") == "development":
            raise error
        else:
            return json(Response(
                code=HttpCode.FAIL,
                message=str(error),
                data={}
            ))
